//package dk.simonvogensen.itodo.client;
//
//import com.google.gwt.gears.core.client.GearsException;
//import com.google.gwt.gears.database.client.Database;
//import com.google.gwt.gears.localserver.client.LocalServer;
//import com.google.gwt.gears.localserver.client.ManagedResourceStore;
//import com.google.gwt.user.client.Command;
//import com.google.gwt.user.client.Timer;
//import com.google.gwt.user.client.rpc.AsyncCallback;
//
//public class GearsBackend extends Backend {
//	private static final int UPDATE_TODO_DELAY = 5000;
//	private static final String RESOURCE_STORE_NAME = "itodo-store";
//	private static final String MANIFEST_URL = "manifest.mf";
//
//	private Database db;
//	private ITodoView view;
//	private ITodoBackend backend;
//
//	public GearsBackend(ITodoView view, ITodoBackend backend) {
//        this.view = view;
//        view.setBackend(this);
//        this.backend = backend;
//    }
//
//    public void init() {
//        backend.init();
//        if(isGearsInstalled()) {
//            createManagedResourceStore2();
////		    createDatabase();
//        } else {
//            view.showAlert("Gears not found - offline option disabled..");
//        }
//    }
//
//    private void createManagedResourceStore2() {
//        LocalServer localServer;
//        try {
//          localServer = new LocalServer();
//          ManagedResourceStore managedResourceStore = localServer.openManagedResourceStore(RESOURCE_STORE_NAME);
//          if (managedResourceStore == null) {
////            oldManagedResourceStore.setManifestURL("");
////            localServer.removeManagedResourceStore(RESOURCE_STORE_NAME);
////            oldManagedResourceStore = localServer.openManagedResourceStore(RESOURCE_STORE_NAME);
//
//              managedResourceStore = localServer.createManagedResourceStore(RESOURCE_STORE_NAME);
//              managedResourceStore.setManifestURL(MANIFEST_URL);
//              managedResourceStore.checkForUpdate();
//
//              final ManagedResourceStore managedResourceStore1 = managedResourceStore;
//              new Timer() {
//                public void run() {
//                  switch (managedResourceStore1.getUpdateStatus()) {
//                    case ManagedResourceStore.UPDATE_OK:
//                      view.showAlert("Ready to go offline.");
//                      break;
//                    case ManagedResourceStore.UPDATE_CHECKING:
//                    case ManagedResourceStore.UPDATE_DOWNLOADING:
//                      view.showAlert("Downloading resources for offline usage..");
//                      schedule(1000);
//                      break;
//                    case ManagedResourceStore.UPDATE_FAILED:
//                        view.showAlert(managedResourceStore1.getLastErrorMessage());
//                      break;
//                  }
//                }
//              }.schedule(1000);
//          }
//
//        } catch (GearsException e) {
//            view.showAlert(e.getMessage());
//        }
//    }
//
//    private void createManagedResourceStore() {
//	    LocalServer localServer;
//	    try {
//	      localServer = new LocalServer();
//	      ManagedResourceStore oldManagedResourceStore = localServer.openManagedResourceStore(RESOURCE_STORE_NAME);
//	      if (oldManagedResourceStore != null) {
//	        oldManagedResourceStore.setManifestURL("");
//	        localServer.removeManagedResourceStore(RESOURCE_STORE_NAME);
//	        oldManagedResourceStore = localServer.openManagedResourceStore(RESOURCE_STORE_NAME);
//	      }
//
//	      final ManagedResourceStore managedResourceStore = localServer.createManagedResourceStore(RESOURCE_STORE_NAME);
//	      managedResourceStore.setManifestURL(MANIFEST_URL);
//	      managedResourceStore.checkForUpdate();
//
//	      new Timer() {
//	        public void run() {
//	          switch (managedResourceStore.getUpdateStatus()) {
//	            case ManagedResourceStore.UPDATE_OK:
//	              view.showAlert("Ready to go offline.");
//	              break;
//	            case ManagedResourceStore.UPDATE_CHECKING:
//	            case ManagedResourceStore.UPDATE_DOWNLOADING:
//	              view.showAlert("Downloading resources for offline usage..");
//	              schedule(1000);
//	              break;
//	            case ManagedResourceStore.UPDATE_FAILED:
//	            	view.showAlert(managedResourceStore.getLastErrorMessage());
//	              break;
//	          }
//	        }
//	      }.schedule(1000);
//
//	    } catch (GearsException e) {
//	    	view.showAlert(e.getMessage());
//	    }
//	}
//
//	private static native boolean isGearsInstalled() /*-{
//	  try {
//	  return $wnd.google.gears.factory != null;
//	  } catch (e) {
//	  return false;
//	  }
//	  }-*/;
//
//	public void getTodoItemList(AsyncCallback callback) {
//		backend.getTodoItemList(callback);
//	}
//
//	public void createTodo(AsyncCallback callback) {
//		backend.createTodo(callback);
//	}
//
//	public void deleteTodo(TodoItem item, AsyncCallback callback) {
//		backend.deleteTodo(item, callback);
//	}
//
//	public void updateTodo(TodoItem item, AsyncCallback callback) {
//		backend.updateTodo(item, callback);
//	}
//
//
////	public TodoItem getTodoItem(int id) {
////		TodoItem item = null;
////		try {
////			ResultSet rs = db.execute("SELECT id, headertext, text, clientversion, serverversion FROM todoitem WHERE id="+id);
////			if(rs.isValidRow()) {
////				item = new TodoItem(rs.getFieldAsInt(0), rs.getFieldAsString(2),
////						rs.getFieldAsInt(3), rs.getFieldAsInt(4));
////			}
////			rs.close();
////		} catch (DatabaseException e) {
////			view.showAlert(e.toString());
////		}
////		return item;
////	}
////
////
////	private void createDatabase() {
////		try {
////			db = new Database("itodo");
////			db.execute("CREATE TABLE IF NOT EXISTS todoitem (id int, headertext varchar(255), text varchar(2550), clientversion int, serverversion int)");
////		} catch (GearsException e) {
////			view.showAlert(e.toString());
////		}
////	}
////
////	public List getTodoItemList() {
////		List itemHeaderList = new ArrayList();
////		try {
////			ResultSet rs = db.execute("SELECT id, headertext, clientversion, serverversion FROM todoitem ORDER BY id DESC");
////			for (int i = 0; rs.isValidRow(); ++i, rs.next()) {
////				itemHeaderList.add(new TodoItem(rs.getFieldAsInt(0), rs.getFieldAsString(1), rs.getFieldAsInt(2), rs.getFieldAsInt(3)));
////			}
////			rs.close();
////		} catch (DatabaseException e) {
////			view.showAlert(e.toString());
////		}
////		return itemHeaderList;
////	}
////
////	public TodoItem createTodo() {
////        try {
////			ResultSet rs = db.execute("SELECT MAX(id) FROM todoitem");
////			int id = -1000+rs.getFieldAsInt(0)+1;
////			db.execute("INSERT INTO todoitem values (?, ?, ?, ?, ?)", new String[] {""+id, "", "","0","0"});
////			return new TodoItem(id, "", 0,0);
////		} catch (DatabaseException e) {
////			view.showAlert(e.toString());
////		}
////		return null;
////	}
////
////	public void updateTodoItem(int id, int newid, String text, String headerText) {
////		try {
////			db.execute("UPDATE todoitem SET id="+newid+", text='"+text+"', headertext='"+headerText+"' WHERE id="+id);
////		} catch (DatabaseException e) {
////			view.showAlert(e.toString());
////		}
////	}
////	public void updateTodo(int id, TodoItem item) {
////		try {
////			db.execute("UPDATE todoitem SET id="+item.getId()+", text='"+item.getText()+"', headertext='"+item.getHeaderText()+"' WHERE id="+id);
////		} catch (DatabaseException e) {
////			view.showAlert(e.toString());
////		}
////	}
////
////	public int getNextTodo(int selectedId) {
////        try {
////			ResultSet rs = db.execute("SELECT MIN(id) FROM todoitem WHERE id > "+selectedId);
////			return rs.getFieldAsInt(0);
////		} catch (DatabaseException e) {
////			view.showAlert(e.toString());
////		}
////		return Integer.MIN_VALUE;
////	}
////
////	public int getPreviousTodo(int selectedId) {
////        try {
////			ResultSet rs = db.execute("SELECT MAX(id) FROM todoitem WHERE id < "+selectedId);
////			return rs.getFieldAsInt(0);
////		} catch (DatabaseException e) {
////			view.showAlert(e.toString());
////		}
////		return Integer.MIN_VALUE;
////	}
////
////	public void deleteTodo(TodoItem item) {
////        try {
////			db.execute("DELETE FROM todoitem WHERE id="+item.getId());
////		} catch (DatabaseException e) {
////			view.showAlert(e.toString());
////		}
////	}
////
////	public void cancelUpdateTimer() {
////    	updateTimer.cancel();
////	}
////
////	public void refreshUpdateTimer() {
////		updateTimer.schedule(UPDATE_TODO_DELAY);
////	}
////
////	Timer updateTimer;
////
////	public void initUpdateTimer(final Command callback) {
////		updateTimer = new Timer() {
////			public void run() {
////				callback.execute();
////			}
////		};
////	}
////
////	public void sendRequest(final String requestString, final AsyncCallback callback) {
////		System.out.println("Request: "+requestString);
////		RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, requestString);
////		try {
////			builder.sendRequest(null, new RequestCallback() {
////				public void onError(Request request, Throwable exception) {
////					callback.onFailure(exception);
////				}
////				public void onResponseReceived(Request request, Response response) {
////					System.out.println("Response: "+response.getText());
////					Object obj = null;
////					if(requestString.indexOf("?cmd=sync") != -1) obj = parseSyncResponse(response.getText());
////					else if(requestString.indexOf("?cmd=create") != -1) obj = parseCreateResponse(response.getText());
////					else if(requestString.indexOf("?cmd=get") != -1) obj = parseGetResponse(response.getText());
////					callback.onSuccess(obj);
////				}
////			});
////		} catch (RequestException e) {
////			view.showAlert(e.getMessage());
////		}
////	}
////
////	protected Integer parseCreateResponse(String xml) {
////		Document document = XMLParser.parse(xml);
////        NodeList listNodeList = document.getElementsByTagName("id");
////        return Integer.valueOf(getElementValue(listNodeList.item(0)));
////	}
////
////	protected TodoItem parseGetResponse(String xml) {
////		Document document = XMLParser.parse(xml);
////        NodeList listNodeList = document.getElementsByTagName("todoitem");
////    	int id = 0;
////    	String text = null;
////    	String headerText = null;
////    	int clientVersion = 0;
////		int serverVersion = 0;
////
////        NodeList itemNodeList = listNodeList.item(0).getChildNodes();
////        for (int j = 0; j < itemNodeList.getLength(); j++) {
////            String nodeName = itemNodeList.item(j).getNodeName();
////            if("id".equals(nodeName)) {
////				id = Integer.parseInt(getElementValue(itemNodeList.item(j)));
////            }
////            else if("text".equals(nodeName)) {
////				text = getElementValue(itemNodeList.item(j));
////            }
////            else if("headertext".equals(nodeName)) {
////				headerText = getElementValue(itemNodeList.item(j));
////            }
////            else if("clientversion".equals(nodeName)) {
////				clientVersion = Integer.parseInt(getElementValue(itemNodeList.item(j)));
////            }
////            else if("serverversion".equals(nodeName)) {
////				serverVersion = Integer.parseInt(getElementValue(itemNodeList.item(j)));
////            }
////        }
////		return new TodoItem(id, text, clientVersion, serverVersion);
////	}
////
////	protected List parseSyncResponse(String xml) {
////		List syncItemList = new ArrayList();
////		Document document = XMLParser.parse(xml);
////        NodeList listNodeList = document.getElementsByTagName("todoitem");
//////        System.out.println("length:"+listNodeList.getLength());
////        for (int i = 0; i < listNodeList.getLength(); i++) {
////        	int id = 0;
////        	int serverId = 0;
////        	String state = "";
////            NodeList itemNodeList = listNodeList.item(i).getChildNodes();
////            for (int j = 0; j < itemNodeList.getLength(); j++) {
////	            String nodeName = itemNodeList.item(j).getNodeName();
////	            if("id".equals(nodeName)) {
////					id = Integer.parseInt(getElementValue(itemNodeList.item(j)));
////	            }
////	            else if("serverid".equals(nodeName)) {
////					serverId = Integer.parseInt(getElementValue(itemNodeList.item(j)));
////	            }
////	            else if("state".equals(nodeName)) {
////					state = getElementValue(itemNodeList.item(j));
////	            }
////            }
////        	syncItemList.add(new SyncItem(id, serverId, state));
////        }
////        return syncItemList;
////	}
////
////    private String getElementValue(Node n) {
////        if(n.hasChildNodes())
////            return n.getFirstChild().getNodeValue();
////        else
////            return null;
////    }
////
////	public String encodeComponent(String text) {
////		return URL.encodeComponent(text);
////	}
////
//}
